package com.yazi.mxz.common.service.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.myframework.smhj.common.exception.MyEntityNotExistsException;
import com.myframework.smhj.common.exception.MyException;
import com.myframework.smhj.common.exception.MyIllegalArgumentException;
import com.myframework.smhj.common.tool.DateUtil;
import com.myframework.smhj.hibernate.dao.BasicService;
import com.myframework.smhj.hibernate.dao.Dao;
import com.yazi.mxz.common.db.dao.MemberDao;
import com.yazi.mxz.common.db.dao.MemberNoticeDao;
import com.yazi.mxz.common.db.dao.NoticeDao;
import com.yazi.mxz.common.entity.ValueFactory;
import com.yazi.mxz.common.entity.beans.Notice;
import com.yazi.mxz.common.service.NoticeService;

@Service("noticeService")
public class NoticeServiceImpl extends BasicService<Notice> implements NoticeService {
	private static Logger log = LoggerFactory.getLogger(NoticeServiceImpl.class);

	@Resource
	NoticeDao noticeDao;
	@Resource
	MemberDao memberDao;
	@Resource
	MemberNoticeDao memberNoticeDao;

	@Override
	protected Dao<Notice> getDao() {
		return noticeDao;
	}
	
	@Override
	public Notice add(Notice notice) {
		log.debug("add：title={}", notice.getTitle());
		ValueFactory.validate(notice);
		notice.setAddTime(DateUtil.getTimeStamp());
		notice.setNoticeId(null);
		return noticeDao.persist(notice);
	}

	@Override
	public void remove(long noticeId) {
		log.debug("remove：noticeId={}", noticeId);
		// 删除所有用户相应的通知
		memberNoticeDao.deleteByNoticeId(noticeId);
		// 删除通知
		Notice notice = noticeDao.get(noticeId);
		if (null != notice) {
			noticeDao.delete(notice);
		}
	}

	@Override
	public Notice edit(Notice notice) throws MyException {
		Long noticeId = notice.getNoticeId();
		log.debug("modify：noticeId={}", noticeId);
		if (null == noticeId) {
			throw new MyIllegalArgumentException();
		}
		Notice oldNotice = noticeDao.get(noticeId);
		if (null == oldNotice) {
			throw new MyEntityNotExistsException();
		}
		ValueFactory.combine(notice, oldNotice);
		return noticeDao.merge(oldNotice);
	}

}
